import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import {Modal} from "antd";
/**创建 axios 实例 */
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    // timeout: 50000,// 接口超时
    headers: { "Content-Type": "application/json;charset=utf-8" },
});
// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = token;
        }
        return config;
    },
    (error: any) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        const { code, msg } = response.data;
        if (code === 0) {
            return response.data;
        }
        // 响应数据为二进制流处理(Excel导出)
        if (response.data instanceof ArrayBuffer || response.data instanceof Blob) {
            return response;
        }
        // token 过期,重新登录
        if (code === 50002) {
            Modal.confirm({
                title: '系统提示',
                content: '登录已过期，请重新登录',
                okText: '重新登录',
                cancelButtonProps: {
                    style: {
                        display: 'none'
                    }
                },
                onOk: () => {
                    localStorage.removeItem('token');
                    window.location.href = '/login';
                }
            });
        } else {
            return response.data
        }
    },
    (error: any) => {
        return Promise.reject(error.message);
    }
);

// 导出 axios 实例
export default service;
